package com.gtw.modules.sys.controller;

import com.gtw.common.utils.PageUtils;
import com.gtw.common.utils.Query;
import com.gtw.common.utils.R;
import com.gtw.modules.entity.TbAnnouncement;
import com.gtw.modules.sys.service.SysTbAnnouncementService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;
import java.util.Map;

/** 公告controller
 * Created by wuye on 2018/2/2.
 */
@RestController
@RequestMapping("/sys/announcement")
public class SysAnnouncementController extends AbstractController{

    @Autowired
    private SysTbAnnouncementService announcementService;

    /**
     * 列表
     */
    @RequestMapping("/list")
    @RequiresPermissions("sys:announcement:list")
    public R list(@RequestParam Map<String, Object> params){
        //查询列表数据
        Query query = new Query(params);

        List<TbAnnouncement> announcementList = announcementService.queryList(query);
        int total = announcementService.queryTotal(query);

        PageUtils pageUtil = new PageUtils(announcementList, total, query.getLimit(), query.getPage());

        return R.ok().put("page", pageUtil);
    }


    /**
     * 信息
     */
    @RequestMapping("/info/{id}")
    @RequiresPermissions("sys:announcement:info")
    public R info(@PathVariable("id") Integer id){
        TbAnnouncement announcement = announcementService.queryObject(id);

        return R.ok().put("announcement", announcement);
    }

    /**
     * 保存
     */
    @RequestMapping("/save")
    @RequiresPermissions("sys:announcement:save")
    public R save(@RequestBody TbAnnouncement announcement){
        announcement.setCreatetime(new Date());
        announcement.setCreateuser(getUser().getUsername());
        announcement.setUpdatetime(new Date());
        announcement.setUpdateuser(getUser().getUsername());
        announcement.setIsdelete(0);
        announcementService.save(announcement);

        return R.ok();
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    @RequiresPermissions("sys:announcement:update")
    public R update(@RequestBody TbAnnouncement announcement){
        announcement.setUpdatetime(new Date());
        announcement.setUpdateuser(getUser().getUsername());
        announcementService.update(announcement);
        return R.ok();
    }

    /**
     * 删除(软删除)
     */
    @RequestMapping("/delete")
    @RequiresPermissions("sys:announcement:delete")
    public R delete(@RequestBody Integer[] ids){
        for(int i = 0; i<ids.length;i++){
            TbAnnouncement tbAnnouncement = announcementService.queryObject(ids[i]);
            tbAnnouncement.setIsdelete(1);
            announcementService.update(tbAnnouncement);
        }
        return R.ok();
    }
}
